package com.demo.mqtt.common.config;

import com.demo.mqtt.common.dto.MqttDto;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.integration.channel.DirectChannel;
import org.springframework.integration.core.MessageProducer;
import org.springframework.integration.mqtt.core.DefaultMqttPahoClientFactory;
import org.springframework.integration.mqtt.core.MqttPahoClientFactory;
import org.springframework.integration.mqtt.inbound.MqttPahoMessageDrivenChannelAdapter;
import org.springframework.integration.mqtt.outbound.MqttPahoMessageHandler;
import org.springframework.integration.mqtt.support.DefaultPahoMessageConverter;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessageHandler;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;

/**
 * @program: mqtt
 * @description: 配置类
 * @author: liuYunKai
 * @create: 2021-03-24 10:50
 */
@Slf4j
@Configuration
public class MqttConfig {

    @Autowired
    private MongoTemplate mongoTemplate;
    @Value("${mqtt.server.url}")
    private String url = "1192.168.174.131";
    @Value("${mqtt.server.port}")
    private String port = "1883";
    @Value("${mqtt.server.username}")
    private String username = "admin";
    @Value("${mqtt.server.password}")
    private String password = "123456";
    @Value("${mqtt.client.consumerId}")
    private String consumerId = "consumerClient";
    @Value("${mqtt.client.publishId}")
    private String publishId = "publishClient";
    @Value("${mqtt.default.topic}")
    private String topic = "topic";
    @Value("${mqtt.default.completionTimeout}")
    private Integer completionTimeout = 3000;

    /**
     * @description 创建MqttPahoClientFactory，设置MQTT Broker连接属性，如果使用SSL验证，也在这里设置。
     */
    @Bean
    public MqttPahoClientFactory mqttClientFactory() {
        DefaultMqttPahoClientFactory factory = new DefaultMqttPahoClientFactory();
        MqttConnectOptions options = new MqttConnectOptions();
        options.setUserName(username);
        options.setPassword(password.toCharArray());
        //多个服务器地址时处理
        String[] strings = url.split(",");
        String[] serverUrls = new String[strings.length];
        if (strings.length > 0) {
            for (int i = 0; i < strings.length; i++) {
                String serverUrl = "tcp://" + strings[i] + ":" + port;
                serverUrls[i] = serverUrl;
            }
        }
        options.setServerURIs(serverUrls);
        factory.setConnectionOptions(options);
        return factory;
    }


    //--------------------------------- 接收消息部分 ------------------------------------------

    /**
     * @param
     * @return adapter
     * 接收消息 配置及订阅消息
     */
    @Bean
    public MessageProducer inbound() {
        //这里要设置接收的topic,要写成动态添加的方式，后续新增设备时不用设置
        //获取所有要订阅的topic
        List<MqttDto> topicDOS = new ArrayList<>();

        String[] topics = new String[topicDOS.size()];
        if (topicDOS != null && topicDOS.size() > 0) {
            for (int i = 0; i < topicDOS.size(); i++) {
                topics[i] = topicDOS.get(i).getTopic();
            }
        }
        MqttPahoMessageDrivenChannelAdapter adapter = new MqttPahoMessageDrivenChannelAdapter(consumerId,
                mqttClientFactory(), topics);
        adapter.setCompletionTimeout(completionTimeout);
        adapter.setConverter(new DefaultPahoMessageConverter());
        // 设置服务质量
        // 0 最多一次，数据可能丢失;
        // 1 至少一次，数据可能重复;
        // 2 只有一次，有且只有一次;最耗性能
        adapter.setQos(1);
        adapter.setOutputChannel(mqttInputChannel());
        return adapter;
    }

    @Bean
    public MessageChannel mqttInputChannel() {
        return new DirectChannel();
    }

    /**
     * @description 消费消息
     * ServiceActivator注解表明当前方法用于处理MQTT消息，inputChannel参数指定了用于消费消息的channel。
     */
    @Bean
    @ServiceActivator(inputChannel = "mqttInputChannel")
    public MessageHandler handler() {
        return message -> {
            String payload = message.getPayload().toString();
            String topic = message.getHeaders().get("mqtt_receivedTopic").toString();
            //用线程池处理订阅到的消息
            try {
                dealMessageByThreadPool(payload, topic);
            } catch (ExecutionException e) {
                e.printStackTrace();
                log.error("处理订阅出错：" + e.getMessage());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        };
    }


    /**
     * @param
     * @return 多线程处理收到的传感器推送, 线程处理参考：
     * https://www.bbsmax.com/A/mo5kxvPvdw/（这里注释掉线程的使用，保持数据的一致性
     * 在处理某一次上报的数据时可以用多线程，提高效率，不能每次订阅数据都起一个线程让它单独处理）
     * 要根据厂商提交的设备id及主题先把所有设备的主题管理起来，一个设备对应一个或多个主题
     */
    public void dealMessageByThreadPool(String payload, String topic) throws ExecutionException, InterruptedException {

        //保存mongodb部分
        log.info(": 处理消息 " + payload);
        //通用保存到mongodb的方法（集合存在则新增，不存在则先创建再新增）
        mongoTemplate.insert(payload, topic);

    }

//--------------------------------发送消息部分-------------------------------------------

    /**
     * @description 发送消息
     */
    @Bean
    public MessageChannel mqttOutboundChannel() {
        return new DirectChannel();
    }

    /*****
     * 发送消息和消费消息Channel可以使用相同MqttPahoClientFactory
     * @return
     */
    @Bean
    @ServiceActivator(inputChannel = "mqttOutboundChannel")
    public MessageHandler outbound() {
        // 在这里进行mqttOutboundChannel的相关设置
        MqttPahoMessageHandler messageHandler =
                new MqttPahoMessageHandler(publishId, mqttClientFactory());
        messageHandler.setAsync(true); //如果设置成true，发送消息时将不会阻塞。
        messageHandler.setDefaultTopic(topic);
        return messageHandler;
    }
}
